package database.tree;

import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;

import myutil.MyUtil;

public class Node implements Serializable, Comparable<Node> {
	private static final long serialVersionUID = 1L;
	private boolean isLeaf;
	private boolean isRoot;
	private boolean isDel;
	private Map<String, Key> keyMap;
	//the last children node for the internal node
	//because the internal node must to have the number of pointer greater than the number of key 
	private Node lastPointer;
	private Node parent;

	// constructor
	public Node() {
		super();
		this.parent = null;
		this.isDel = false;
		this.isLeaf = false;
		this.isRoot = false;
		this.keyMap = new TreeMap<String, Key>();
		this.lastPointer = null;
	}
	
	public Node(boolean isLeaf, boolean isRoot) {
		super();
		this.parent = null;
		this.isLeaf = isLeaf;
		this.isRoot = isRoot;
		this.isDel = false;
		this.keyMap = new TreeMap<String, Key>();
		this.lastPointer = null;
	}

	// Functional method
	private int capacity(){
		return (this.lastPointer == null) ? keyMap.size() : keyMap.size()+1;
	}
	
	public boolean isFull() {
		return capacity() > MyUtil.M;
	}
	
	public void addKey(Key key) {
//		if( this.keyMap.containsKey(key.getKeyString()) ){
//			System.out.println("DDDDDDDDDDDDDDDDDDDDDDD");
//		}else{
//			System.out.println("iiiiiiiiiiiiiiiiiiiiiiii");
//		}
		this.keyMap.put(key.getKeyString(), key);
	}

	public void deleteKey(String key) {
		this.keyMap.get(key).setDel(true);
	}
	public boolean isContainNode(String key){
		return this.keyMap.containsKey(key);
	}
	// getter and setter
	public boolean isLeaf() {
		return isLeaf;
	}

	public void setLeaf(boolean isLeaf) {
		this.isLeaf = isLeaf;
	}

	public boolean isRoot() {
		return isRoot;
	}

	public void setRoot(boolean isRoot) {
		this.isRoot = isRoot;
	}

	public boolean isDel() {
		return isDel;
	}

	public void setDel(boolean isDel) {
		this.isDel = isDel;
	}

	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}
	
	public Map<String, Key> getKeyMap(){
		return this.keyMap;
	}

	public Node getLastPointer() {
		return lastPointer;
	}

	public void setLastPointer(Node lastPointer) {
		this.lastPointer = lastPointer;
	}

	@Override
	public int compareTo(Node o) {
		int r = this.keyMap.entrySet().iterator().next().getKey().compareTo(o.getKeyMap().entrySet().iterator().next().getKey());
		return r;
	}
}
